import MqttObserver from '../mqtt/mqtt_observer';
import MqttManager from '../mqtt/mqtt_manager';
import HttpService from './http_service';
import { decryptAES } from '../utils/aes';
import Logger from '../utils/logger';

/**
 * MqttService
 * 
 * 该类封装了 MQTT 服务的连接、订阅、消息分发等逻辑。
 * 它继承自 HttpService，并实现了 MqttObserver 接口，可监听 MQTT 连接状态与消息事件。
 */
export default class MqttService extends HttpService implements MqttObserver {

  private eventListeners: Map<string, Set<Function>> = new Map();

  private deviceId?: string;

  public addMqttEventListener(type: string, listener: Function) {
    const listeners = this.eventListeners.get(type) || new Set();
    listeners.add(listener);
    this.eventListeners.set(type, listeners);
    Logger.log(`添加设备监听`, type);
  }

  public removeMqttEventListener(type: string, listener: Function) {
    const listeners = this.eventListeners.get(type) || new Set();
    listeners.delete(listener);
  }
  
  constructor() {
    super();
    // MqttManager.init({
    //  brokerUrl: "ws://test.derucci-smart.com:8083/mqtt",
		// 	username: "elfTv",
		// 	password: "123698745",
    // });

    // MqttManager.init({
    //   brokerUrl: "wss://10.16.2.79:32195/mqtt",
		// 	username: "testUser",
		// 	password: "123698745",
    // });

    // MqttManager.init({
    //   brokerUrl: "wss://test-ws.derucci-smart.com/mqtt",
		// 	username: "lite-mini",
		// 	password: "Kx5tr3HDcjQk"
    // });

    // 生产
    // MqttManager.init({
    //   brokerUrl: "wss://ws.derucci-smart.com:443/mqtt",
		// 	username: "lite-mini",
		// 	password: "b6fFqYKx236P",
    // });
    // MqttManager.addObserver(this);
    // MqttManager.subscribe("u/c/common/3/61cb3b816f2156b02660a7e15a687470");
  }

  // 连接mqtt 并订阅设备主题
  public async connectToMqtt(deviceId: string) {
    this.deviceId = deviceId;
    const res: any = await this.getMqttConnectConfig();
    if (res.code === 200) {
      const data = JSON.parse(decryptAES(res.data.enStr));
      MqttManager.init({
        host: data.host,
        port: data.port,
        userName: data.un,
        password: data.psw,
        useSSL: data.port === 443
      });
      // MqttManager.init({
      //   host: "ws.derucci-smart.com",
      //   port: 443,
      //   userName: "lite-mini",
      //   password: "b6fFqYKx236P",
      //   useSSL: true
      // });
      MqttManager.addObserver(this);
      return 0;
    }
    return 1;
  }

  async onConnected() {
    if(this.deviceId == undefined) {
      console.error("调用 derucci.connectToMqtt 方法的时候请传入 deviceId");
      return;
    }
    const res = await this.getMqttSubTopics(this.deviceId!);
    if(res.code === 200) {
      const str = decryptAES(res.data.enStr);
      const json = JSON.parse(str);
      const topic = json.topic[0];
      MqttManager.subscribe(topic);
    } else {
      console.error("获取设备主题失败");
    }
  }
  onDisconnected() {

  }
  
  onSubscribed(topic: string | string[]) {

  }

  onSubscribeFail(topic: string | string[], error: Error) {

  }

  onUnsubscribed(topic: string | string[]) {

  }

  onUnsubscribeFail(topic: string | string[], error: Error) {

  }
  onMessage(topic: string, data: { [key: string]: any; }) {
    const code = data.code;
    if (data.obj && data.obj.data && data.obj.data.enStr) {
      try {
        data.obj.data = JSON.parse(decryptAES(data.obj.data.enStr));
      } catch (e) {
        data.obj.data = decryptAES(data.obj.data.enStr);
      }
    }
    if (this.eventListeners.has("*")) {
      const listeners = this.eventListeners.get("*");
      listeners?.forEach(fn => {
        fn(data);
      });
    }
    if (!this.eventListeners.has(code)) return;
    const listeners = this.eventListeners.get(code);
    listeners?.forEach(fn => {
      fn(data);
    });
  }
}
